<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="top">====================socket测试====================</div>
<div id="msgBody"></div>

<script src="../static/jquery-3.5.1.min.js"></script>
<script src="../static/sockjs.min.js"></script>
<script src="../static/stomp.js"></script>
<script>
    $(function () {
        if ('WebSocket' in window) {
            //初始化WebSocket连接（可以不用在这里初始化）
            openWebSocket();
        } else {
            alert("浏览器不支持WebSocket");
        }
    })

    // WebSocket实例
    var websocket = null;
    // 后台WebSocket连接地址（这里端口、sid写死了，可以考虑优化）
    var wsUrl = "ws://localhost:9880/message/websocket?token=9bd42786943a9fb0bd1d48be546eaea9";

    function openWebSocket() {
        if (websocket == null || websocket.readyState === websocket.CLOSED) {
            websocket = new WebSocket(wsUrl);

            //连接发生错误的回调方法
            websocket.onerror = function (e) {
                console.log(e)
                var msg = "<p style='color:red;'>WebSocket连接错误!!!</p>";
                setMessageInnerHTML(msg);
            };

            //连接成功建立的回调方法
            websocket.onopen = function (e) {
                var msg = "<p style='color:green;'>WebSocket连接成功... ...</p>";
                setMessageInnerHTML(msg);
            };

            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                var msg = "<p style='color:black;'>" + event.data + "</p>";
                setMessageInnerHTML(msg);
            };

            //连接关闭的回调方法
            websocket.onclose = function (e) {
                console.log(e)
                var msg = "<p style='color:red;'>服务端关闭WebSocket连接!!!</p>";
                setMessageInnerHTML(msg);
            };

            //监听窗口关闭事件，当窗口关闭或页面刷新时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
                websocket = null;
            };
        }
    }

    function setMessageInnerHTML(msg){
        $('#msgBody').append(msg);
    }


    //关闭连接
    function closeWebSocket() {
        websocket.close();
        websocket = null;
    }

    //判断WebSocket是否已经连接
    function webSocketIsAvailable() {
        if (websocket == null || websocket.readyState === websocket.CLOSED) {
            return false;
        }

        return true;
    }

    //发送消息
    function send() {
        if (!webSocketIsAvailable()) {
            alert("WebSocket未连接");
            return;
        }
        var msg = "向后台接口发送消息";
        websocket.send(msg);
    }

    //判断字符串是否Json格式
    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }
            } catch(e) {
                return false;
            }
        }
    }
</script>
</body>
</html>